package com.sie.service.impl;

import cn.hutool.json.JSONUtil;
import com.sie.entity.Authority;
import com.sie.entity.Role;
import com.sie.entity.ViewEmp;
import com.sie.entity.ViewEmpLogin;
import com.sie.mapper.EmpMapper;
import com.sie.mapper.LoginMapper;
import com.sie.mapper.RoleMapper;
import com.sie.service.LoginService;
import com.sie.util.ReslUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 登录服务实现类
 */
@SuppressWarnings("all")
@Transactional
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 登录方法
     * @param username
     * @param password
     * @return
     */
    @Override
    public Map login(String username, String password) {
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return ReslUtil.fail();
        }
//        查询账户是否存在
        ViewEmpLogin user = loginMapper.login(username);
        if (user == null) {
            return ReslUtil.fail();
        }
//        如果状态为失效，则禁止登录
        ViewEmp viewEmp1 = empMapper.selectById(user.getEmpId());
        if ("0".equals(viewEmp1.getEmpStatus())) {
            return ReslUtil.fail();
        }
//        获取密码密文
        String ciphertext = DigestUtils.md5DigestAsHex((password + user.getLoginSalt()).getBytes());
//        判断密码是否正确
        if (user.getLoginPassword().equals(ciphertext)) {
//            查询登陆账户权限及信息
            String empId = user.getEmpId();
            List<Role> roles = roleMapper.findRoles(empId);
            Iterator<Role> iterator = roles.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().getRoleStatus().equals("0")) {
                    iterator.remove();
                }
            }
//            创建权限去重集合
            HashSet<Authority> authors = new HashSet<>();
//            获取角色所有权限
            roles.forEach(role -> {
                empMapper.authors(String.valueOf(role.getRoleId())).forEach(authority -> {
                    authors.add(authority);
                });
            });
            Iterator<Authority> authIte = authors.iterator();
            while (authIte.hasNext()) {
                if (authIte.next().getAuthStatus().equals("0")) {
                    authIte.remove();
                }
            }
            ViewEmp viewEmp = empMapper.selectById(empId);
            //            除去标准字段ROLE_
            roles.forEach(role -> role.setRoleName(role.getRoleName().substring(5)));
//            出去标准字段AUTH_
            authors.forEach(auth -> auth.setAuthName(auth.getAuthName().substring(5)));
            viewEmp.setRoles(roles);
            viewEmp.setAuthorities(authors);
//            封装token
            String date = LocalDateTime.now().toString();
            String token = "";
            try {
                token = "TIME_" + date + ",USER_" + URLEncoder.encode(JSONUtil.toJsonStr(viewEmp), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.out.println("token异常");
            }

            HashMap hashMap = new HashMap() {{
                put("res", true);
                put("user", viewEmp);
            }};
            hashMap.put("token", token);
            return hashMap;
        }
        return ReslUtil.fail();

    }
}
